<template>
  <a-card title="Formily Dynamic Form Example" style="width: 100%; max-width: 600px; margin: 0 auto; padding: 20px;">
    <a-button @click="changeTitle">改变标题</a-button>
    {{ schema.properties.input.title }}
    <FormProvider :form="form" :key="formKey" v-if="show" > <!-- 更新 FormProvider 的 key -->
      <SchemaFields.SchemaField :schema="schema" :schemaKey="schemaKey"/>
      <Submit @submit="log">提交</Submit>
      <Reset>重置</Reset>
    </FormProvider>
  </a-card>
</template>

<script setup>
import { ref, nextTick } from 'vue';
import { createForm } from '@formily/core';
import { FormProvider, createSchemaField } from '@formily/vue';
import { Input, InputNumber, FormItem, Select, Switch, FormGrid } from '@formily/antdv-x3';

const SchemaFields = createSchemaField({
  components: {
    Input,
    InputNumber,
    Select,
    FormItem,
    Switch,
    FormGrid,
  },
});

const form = ref(createForm());

// 定义一个 formKey 用于强制刷新 FormProvider
const formKey = ref(0);

const schema = ref({
  type: 'object',
  properties: {
    input: {
      type: "string",
      title: "账号",
      required: true,
      "x-decorator": "FormItem",
      "x-component": "Input",
      "x-component-props": {
        placeholder: "请输入",
        allowClear: true,
        style: {
          width: '20%',
        },
      },
    },
  },
}); 

const show = ref(true);
const schemaKey = ref(0);

const changeTitle = () => {
  // 深度更新 schema 中的字段
  schema.value.properties.input.title += "1";
  show.value = false;
  // 使用 $nextTick 确保视图更新后再修改 key
  nextTick(() => {
    // 更新 schemaKey 来强制刷新 SchemaField
    schemaKey.value += 1;
    
    // 更新 formKey 来强制刷新 FormProvider
    formKey.value += 1;
    show.value = true;
    // 调用 form 的 forceUpdate 强制刷新
    // form.value?.forceUpdate(); 
  });

  console.log('Updated schema:', schema.value);
};

const log = (values) => {
  console.log('提交的表单数据:', values);
};
</script>

<style scoped lang="less">
a-card {
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

a-card .ant-card-body {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.form-item {
  margin-bottom: 16px;
}

.ant-input,
.ant-input-number,
.ant-select {
  width: 100%;
}

/deep/.formily-antdv-form-item {
  display: block !important;
}

/deep/.formily-antdv-form-item-label-align-right>.formily-antdv-form-item-label {
  justify-content: flex-start;
}

/deep/.formily-antdv-form-item-control-align-left .formily-antdv-form-item-control-content {}
</style>
